const SettingsService = require('../service/settings');
const settingsService = new SettingsService();
module.exports = (app) => {
  app.post(`${process.env.VUE_APP_BASE_API}/settings/info`, async (req, res) => {
    const { userInfo } = req;
    try {
      const result = await settingsService.first({ organizationId: userInfo.organizationId });
      if (result) {
        return res.json({
          code: 20000,
          data: result,
        });
      }
      return res.json({
        code: 20000,
        data: {},
      });
    } catch (error) {
      return res.json({
        code: 500,
        message: error.message || '更新失败',
      });
    }
  });

  app.post(`${process.env.VUE_APP_BASE_API}/settings/update`, async (req, res) => {
    const { userInfo, body } = req;
    try {
      const existOrgSetting = await settingsService.first({ organizationId: userInfo.organizationId });
      if (existOrgSetting) {
        const updateRes = await settingsService.update(existOrgSetting.id, body);
        return res.json({
          code: 20000,
          isSuccess: updateRes,
        });
      }
      const record = await settingsService.create({ ...body, organizationId: userInfo.organizationId, operator: userInfo.id });
      return res.json({
        code: 20000,
        isSuccess: !!record,
        settings: record,
      });
    } catch (error) {
      return res.json({
        code: 500,
        message: error.message || '操作失败',
      });
    }
  });
};
